package com.cctc.rds.nrpc.core.protocol.serializer.impl;

import com.cctc.rds.nrpc.core.protocol.serializer.Serializer;
import com.cctc.rds.nrpc.core.protocol.serializer.SerializerType;

import java.io.*;

public class JdkSerializer implements Serializer {
    @Override
    public Byte getSerializerType() {
        return SerializerType.JDK.getValue();
    }

    @Override
    public byte[] serialize(Object o) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(o);
            return baos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public <T> T deserialize(Class<T> tClass, byte[] data) {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
             ObjectInputStream ois = new ObjectInputStream(bais)) {
            return (T) ois.readObject();
        } catch (ClassNotFoundException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}
